import axios from 'axios'
import router from '@/router/index';
import {getToken} from '@/utils/auth'
import {useUserStore} from "@/store/modules/user";
import { ElMessage } from 'element-plus'

// 创建两个 axios 实例
const service = axios.create({
  baseURL: import.meta.env.VITE_APP_BASE_API,
  timeout: 18000
})

const tenantService = axios.create({
  baseURL: import.meta.env.VITE_APP_TENANT_API,
  timeout: 18000
})

axios.defaults.retry = 3
axios.defaults.retryDelay = 2000

// 统一的拦截器配置函数
const setupInterceptors = (service) => {
  // request拦截器
  service.interceptors.request.use(config => {

    
    
    if (useUserStore().token) {
      config.headers['Authorization'] = 'Token ' + useUserStore().token 
      config.headers['X-Tenant-ID'] = useUserStore().tenant_id
      
      if(!useUserStore().is_super){
        if(useUserStore().college_id){
          config.headers['saas-id'] = useUserStore().college_id
        }else if(useUserStore().roles[0]&&useUserStore().roles[0].name=="学生组"){

          config.headers['saas-id'] = useUserStore().roles[0].parent_id
        }else{
          config.headers['saas-id'] = 1
        }
      }
    }
    config.headers['Content-Type'] = "application/json"

    return config
  }, error => {
    console.log(error)
    return Promise.reject(error)
  })

  // 响应拦截器
  service.interceptors.response.use(
    response => { // 使用完整response对象
      // 成功响应处理（状态码2xx） 
      return response.data;// 返回实际业务数据

    },
    error => {       
      if(error.response.status==401){
        ElMessage.error('Token过期，请重新登录')
        localStorage.clear()
        sessionStorage.clear()
        router.push({path:"/login"})
      }
    return error
    }
  )
}

// 为两个实例添加拦截器
setupInterceptors(service)
setupInterceptors(tenantService)

// 导出两个实例
export { service, tenantService }
export default service  // 保持向后兼容
